package com.strive.common.lock;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/2/21 14:43
 * @Version 1.0
 */
public interface DistributedLock {
    /**
     * 获取锁,如果获取不成功则一直等待知道lock被获取
     * @param key 锁的key
     * @param leaseTime 加锁的时间，超过了这时间后锁便会自动解锁
     * @param unit 参数的时间单位
     * @param isFair
     * @return
     * @throws Exception
     */
    ZLock lock(String key, long leaseTime, TimeUnit unit, boolean isFair) throws Exception;

    default ZLock lock(String key,long leaseTime,TimeUnit unit) throws Exception {
        return this.lock(key,leaseTime,unit,false);
    }

    default ZLock lock(String key,boolean isFair) throws Exception {
        return this.lock(key,-1,null,isFair);
    }

    default ZLock lock(String key) throws Exception {
        return this.lock(key,-1,null,false);
    }

    /**
     *
     * @param key 锁的key
     * @param waitTime 获取锁的最大尝试时间
     * @param leaseTime 枷锁的时间,超过这个时间便自动解锁；如果leastTime为-1，则保持锁定知道显示解锁
     * @param unit 锁对象，如果获取锁失败则为null
     * @return
     * @throws Exception
     */
    ZLock tryLock(String key,long waitTime,long leaseTime,TimeUnit unit,boolean isFair) throws Exception;

    default ZLock tryLock(String key, long waitTime, long leaseTime, TimeUnit unit) throws Exception {
        return this.tryLock(key, waitTime, leaseTime, unit, false);
    }
    default ZLock tryLock(String key, long waitTime, TimeUnit unit, boolean isFair) throws Exception {
        return this.tryLock(key, waitTime, -1, unit, isFair);
    }
    default ZLock tryLock(String key, long waitTime, TimeUnit unit) throws Exception {
        return this.tryLock(key, waitTime, -1, unit, false);
    }

    /**
     * 释放锁
     * @param lock 锁对象
     */
    void unlock(Object lock) throws Exception;

    default void unLock(ZLock zLock) throws Exception{
        if(zLock != null){
            this.unlock(zLock.getLock());
        }
    }
}
